package org.eliza.base.coroutinesx.channel

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*


private fun channelBuffer(time: Int) = runBlocking {
    val channel = Channel<Int>(time, onBufferOverflow = BufferOverflow.SUSPEND)
    launch {
        for (x in 1..10) {
            println("send start $x")
            channel.send(x)
//            channel.close() // close -> send = panic
//                           // close -> receive = panic
        }
        channel.close()
    }
    for (y in channel) {
//        channel.close() -->自动关闭
        delay(100)
        println("send receive ==> ${y}")
    }
//    while (true) {
//        delay(100)
//        println("send receive ==> ${channel.receive()}") //panic
//    }
    println("Done!")
}

private fun fullBuffer() = runBlocking<Unit> {
    val channel = Channel<Int>(4) // create buffered channel
    val sender = launch { // launch sender coroutine
        repeat(10) {
            println("Sending $it") // print before sending each element
            channel.send(it) // will suspend when buffer is full
        }
    }
    // don't receive anything... just wait....
    delay(1000)
    sender.cancel() // cancel sender coroutine
}

private fun main() {
//    channelBuffer(2)
    fullBuffer()
}